﻿using Dapper;
using Microsoft.AspNetCore.Http;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Helpers;
using PersonalWebsite.Core.Result;

namespace PersonalWebsite.Application.Queries.Website
{
    public record GetGameVideoVO
    {
        public int Id { get; init; }
        public string Name { get; init; }   
        public string VideoLink { get; private set; }

        public void SetInternetImageUrl(IHttpContextAccessor httpContextAccessor)
        {
            if (!string.IsNullOrEmpty(VideoLink))
            {
                VideoLink = FileHelper.GetGameCGFile(httpContextAccessor, VideoLink);
            }
        }
    }

    public record GetGameVideoQuery:IQuery<ApiResult<List<GetGameVideoVO>>,List<GetGameVideoVO>>
    {
        
    }

    internal class GetGameVideoQueryHandler : QueryHandler<GetGameVideoQuery, ApiResult<List<GetGameVideoVO>>, List<GetGameVideoVO>>
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IDBConnectionFactory dBConnectionFactory;

        public GetGameVideoQueryHandler(IHttpContextAccessor httpContextAccessor, IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
        {
            this.httpContextAccessor = httpContextAccessor;
            this.dBConnectionFactory = dBConnectionFactory;
        }

        public override async Task<ApiResult<List<GetGameVideoVO>>> Handle(GetGameVideoQuery request, CancellationToken cancellationToken)
        {
            using var dbConnection = dBConnectionFactory.GetDbConnection();
            string sql = "SELECT * FROM WS_GameVideo";
            var data = await dbConnection.QueryAsync<GetGameVideoVO>(sql);

            var result = new List<GetGameVideoVO>();
            if (data != null && data.Any())
            {
                foreach (var item in data)
                {
                    item.SetInternetImageUrl(httpContextAccessor);
                    result.Add(item);
                }
            }

            return await Task.FromResult(ApiResult<List<GetGameVideoVO>>.Success(result));
        }
    }
}
